<template>
    <div class="app-container">
      <el-row :gutter="20" style="width:1375px;">
        <el-col :span="20" :xs="24">
          <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
            label-width="73px">
            <el-form-item label="成果名称" prop="consultingResultName">
              <el-input
                v-model="queryParams.consultingResultName"
                placeholder="请输入成果名称"
                clearable
                style="width: 300px"
                @keyup.enter="handleQuery"
              />
            </el-form-item>
            <el-form-item label="类别" prop="consultingCategory" style="margin-left: -12px;">
              <el-input
                v-model="queryParams.consultingCategory"
                placeholder="请输入成果类别"
                clearable
                style="width: 230px;"
                @keyup.enter="handleQuery"
              />
            </el-form-item>

            <el-form-item>
              <el-button type="primary" icon="Search" size="mini" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
  
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button type="primary" plain icon="Plus" size="mini" @click="handleAdd"
                v-hasPermi="['user:add']">新增</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="success" plain icon="EditPen" size="mini" :disabled="single" @click="handleUpdate"
                v-hasPermi="['user:edit']">修改</el-button>
            </el-col>
            <!-- <el-col :span="1.5">
              <el-button type="danger" plain icon="Delete" size="mini" :disabled="multiple" @click="handleDelete"
                v-hasPermi="['user:remove']">删除</el-button>
            </el-col> -->
            <el-col :span="1.5">
                    <el-button
                       type="info"
                       plain
                       icon="Upload"
                       @click="handleImport"
                       v-hasPermi="['user:import']"
                    >导入</el-button>
                 </el-col>

                 <el-col :span="1.5">
                  <el-button
                     type="warning"
                     plain
                     icon="Download"
                     @click="handleExport"
                     v-hasPermi="['user:export']"
                  >导出</el-button>
               </el-col>
          </el-row>
        </el-col>
      </el-row>
      <el-table :data="tableData" border style="width: 100%" @selection-change="handleSelectionChange">
    <el-table-column type="selection" width="55"></el-table-column>
    <el-table-column prop="consultingId" fixed label="序号" width="80" />
    <el-table-column prop="username" fixed label="姓名" width="110" />
    <el-table-column prop="consultingResultName" label="成果名称" width="300" />
    <el-table-column prop="consultingCategoryy" label="类别" width="200" />
    <el-table-column prop="consultingScore" label="分值" width="100" />
    <el-table-column prop="consultingNotes" label="备注" />
</el-table>
  
      <!-- 新增用户的对话框 -->
      <el-dialog :title="dialogTitle" v-model="dialogVisible" width="30%">
        <el-form ref="userForm" :model="formData" label-width="80px">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="formData.username" placeholder="请输入用户名"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="formData.email" placeholder="请输入邮箱"></el-input>
          </el-form-item>
          <el-form-item label="性别" prop="sex">
            <el-select v-model="formData.sex" placeholder="请选择性别">
              <el-option label="男" value="男"></el-option>
              <el-option label="女" value="女"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="电话号码" prop="phone">
            <el-input v-model="formData.phone" placeholder="请输入电话号码"></el-input>
          </el-form-item>
          <el-form-item label="地址" prop="address">
            <el-input v-model="formData.address" placeholder="请输入地址"></el-input>
          </el-form-item>
          <el-form-item label="角色" prop="role">
            <el-select v-model="formData.role" placeholder="请选择角色">
              <el-option label="用户" value="1"></el-option>
              <el-option label="管理员" value="2"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="handleSubmit">确 定</el-button>
          </span>
        </template>
      </el-dialog>
  
      <!-- 用户导入对话框 -->
      <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
           <el-upload
              ref="uploadRef"
              :limit="1"
              accept=".xlsx, .xls"
              :headers="upload.headers"
              :action="upload.url + '?updateSupport=' + upload.updateSupport"
              :disabled="upload.isUploading"
              :on-progress="handleFileUploadProgress"
              :on-success="handleFileSuccess"
              :auto-upload="true"
              drag
           >
              <el-icon class="el-icon--upload"><upload-filled /></el-icon>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
              <template #tip>
                 <div class="el-upload__tip text-center">
                    <!-- <div class="el-upload__tip">
                       <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据
                    </div> -->
                    <span>仅允许导入xls、xlsx格式文件。</span>
                 </div>
              </template>
           </el-upload>
           <template #footer>
              <div class="dialog-footer">
                 <el-button type="primary" @click="submitFileForm">确 定</el-button>
                 <el-button @click="upload.open = false">取 消</el-button>
              </div>
           </template>
        </el-dialog>
  <!-- 分页组件 -->
  <Pagination v-model="queryParams" :total="total" @change="handleChange" />
      <el-footer>
  
      </el-footer>
    </div>
  </template>
  
  <script setup>
  import { useUserStore } from '@/store/user.js';
  import { ref, onMounted, reactive } from 'vue';
  import { getUserNetworkCulList,addUserNetworkCul,updateUserNetworkCul } from "@/api/academicPapers";
  import { ElMessage, ElMessageBox } from 'element-plus';
  import Pagination from '@/components/Pagination/index.vue';
  
  const tableData = ref([]); // 初始化为响应式数组
  const title = ref("");
  const open = ref(false);
  //处理选中行
  const selectedRow = ref(null);
  
  /** 导入按钮操作 */
  function handleImport() {
    upload.title = "用户导入";
    upload.open = true;
  };
  /*** 用户导入参数 */
  const upload = reactive({
    // 是否显示弹出层（用户导入）
    open: false,
    // 弹出层标题（用户导入）
    title: "",
    // 是否禁用上传
    isUploading: false,
    // 是否更新已经存在的用户数据
    // updateSupport: 0,
    // 上传的地址
    url: "http://localhost:8080/researchProject/importData",
    // headers: {
    //   withCredentials: true
    // },
    // url: import.meta.env.VITE_APP_BASE_API + "/user/importData"
  });

  
  // 对话框相关变量
  const dialogVisible = ref(false);
  const dialogTitle = ref('新增用户');
  const formData = reactive({
    userId: '',
    username: '',
    email: '',
    sex: '',
    phone: '',
    address: '',
    role: ''
  });
  
  // 定义查询参数
  const queryParams = ref({
    consultingResultName: '',
    consultingCategory: '',
    pageSize: 10,
  });
  const total = ref(0);
  // const queryParams = ref({
  //   userKeyword: '',
  // });
  
  // 控制显示/隐藏搜索表单
  const showSearch = ref(true);
  
  // 单选和多选状态
  const single = ref(false);
  const multiple = ref(false);

  
  const handleFileUploadProgress = (event, file, fileList) => {
    upload.isUploading = true; // 开始上传时禁用按钮
  };
  
  const handleFileSuccess = (response, file, fileList) => {
    upload.isUploading = false; // 上传完成后启用按钮
    if (response.code === 200) {
      ElMessage.success("导入成功");
      upload.open = false; // 关闭对话框
      getUserList(); // 刷新用户列表
    } else {
      ElMessage.error(response.message || "导入失败，请检查文件格式或内容");
    }
  };
  

  // 查询方法
  async function handleQuery() {
    try {
      console.log('查询=',queryParams.value)

      const response = await getUserNetworkCulList({
        ...queryParams.value,
        // userId: currentUserId, // 使用 Pinia 中的用户ID
        currentPage: queryParams.value.currentPage, // 分页从1开始
        pageSize: queryParams.value.pageSize
      });
      tableData.value = response.data; // 更新表格数据
      total.value = response.total; // 总条目数
      console.log('查询结果:', response.data);
    } catch (error) {
      console.error('查询失败:', error);
    }
  }
  
  // 重置查询条件
  function resetQuery() {
    queryParams.value = {
      userKeyword: ''
    };
    handleQuery(); // 重置后重新查询
  }
  
  // 显示新增对话框
  function handleAdd() {
    // 清空表单数据
    Object.assign(formData, {
      username: '',
      email: '',
      sex: '',
      phone: '',
      address: '',
      role: ''
    });
    dialogTitle.value = '新增用户';
    dialogVisible.value = true;
  }
  
  // 提交表单到后端
  async function handleSubmit() {
    try {
  
      if (formData.userId) { // 如果存在id，则为修改操作
        const sendData = {
          id: formData.userId,
          username: formData.username,
          email: formData.email,
          sex: formData.sex,
          phone: formData.phone,
          address: formData.address,
          role: formData.role
        };
        await updateUserNetworkCul(sendData); // 调用API进行更新操作
        ElMessage({
          message: '修改成功',
          type: 'success'
        });
      } else { // 否则为新增操作

        await addUserNetworkCul(formData);
        ElMessage({
          message: '新增成功',
          type: 'success'
        });
      }
  
      dialogVisible.value = false; // 关闭对话框
      await handleQuery(); // 刷新列表以显示新添加/修改的记录
    } catch (error) {
      console.error('操作失败:', error);
      ElMessage.error('操作失败，请重试');
    }
  }
  
  function handleSelectionChange(selection) {
    if (selection.length > 0) {
      single.value = selection.length !== 1;
      multiple.value = false; // 当有选择时，允许删除
      selectedRow.value = selection;
    } else {
      single.value = true;
      multiple.value = true; // 没有选择时，不允许删除
      selectedRow.value = null;
    }
  }
  
  //修改
  async function handleUpdate() {
    if (!selectedRow.value) {
      ElMessage.error('请选择一条记录进行修改');
      return;
    }
    // 将选中的行数据赋值给formData
    if (selectedRow.value.length > 0) {
      Object.assign(formData, selectedRow.value[0]);
    }
    // 将选中的行数据赋值给formData
    // Object.assign(formData, JSON.parse(JSON.stringify(selectedRow.value)));
  
    dialogTitle.value = '修改用户';
    dialogVisible.value = true;
  }
  
  //删除
  async function handleDelete() {
    const selectedIds = selectedRow.value.map(row => row.id);
  
    if (!selectedIds || !selectedIds.length) {
      ElMessage.error('请选择一条或多条记录进行删除');
      return;
    }
  
    try {
      await ElMessageBox.confirm(
        '是否确认删除用户编号为"' + selectedIds.join('", "') + '"的数据项？',
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      );
  
      // 调用删除API，现在我们传递的是一个数组
      await delUser(selectedIds);
  
      // 提示删除成功
      ElMessage({
        message: '删除成功',
        type: 'success'
      });
  
      // 刷新列表以显示最新的更改
      await handleQuery();
  
      // 清除选中状态
      selectedRow.value = null;
      single.value = true;
      multiple.value = true;
  
    } catch (error) {
      // 用户取消删除或删除过程中出错
      if (error !== 'cancel') {
        console.error('删除失败:', error);
        ElMessage.error('删除失败，请重试');
      }
    }
  }
  
  const handleChange = (newPage, newPageSize) => {
      queryParams.value.currentPage = newPage;
      queryParams.value.pageSize = newPageSize;
      handleQuery();
  };
  
  // 页面加载时自动查询一次
  onMounted(() => {
    handleQuery();
  });
  
  </script>
  
  <style scoped>
  .el-input__inner {
    margin-left: 2px;
  }
/* 使用深度选择器 */
:deep(.el-input--small .el-input__inner) {
    height: 30px;
    line-height: 30px;
}
:deep(.el-form-item__label) {
    text-align: right;
    vertical-align: middle;
    float: left;
    font-size: 14px;
    color: #606266;
    line-height: 40px;
    padding: 0 12px 0 0;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
}
:deep(.el-form-item) {
    display: flex;
    align-items: center;
    margin-bottom: 18px;
}

.demo-date-picker {
  display: flex;
  width: 100%;
  padding: 0;
  flex-wrap: wrap;
}

.demo-date-picker .block {
  padding: 30px 0;
  text-align: center;
  border-right: solid 1px var(--el-border-color);
  flex: 1;
}

.demo-date-picker .block:last-child {
  border-right: none;
}

.demo-date-picker .container {
  flex: 1;
  border-right: solid 1px var(--el-border-color);
}

.demo-date-picker .container .block {
  border-right: none;
}

.demo-date-picker .container .block:last-child {
  border-top: solid 1px var(--el-border-color);
}

.demo-date-picker .container:last-child {
  border-right: none;
}

.demo-date-picker .demonstration {
  display: block;
  color: var(--el-text-color-secondary);
  font-size: 12px;
  margin-bottom: 20px;
}
.el-form--inline .el-form-item{
  margin-right: 18px !important;
}
  </style>